import Env from '@/env.js'
import {phoneLogin, pwdLogin} from "./api";
const accountInfo = uni.getAccountInfoSync();
const state = {
	//token
	appId: accountInfo.miniProgram.appId,
}
const mutations = {}
const getters = {}
const actions = {
	// 微信登录
	async wxLogin({state, dispatch}, data) {
	    if (!data.detail.code) return
	    uni.showLoading({
	        title: '登录中...'
	    });
	    dispatch('getToken', {phoneCode: data.detail.code}).then(async ref => {
	        await dispatch('getUserInfo')
	        if (uni.getStorageSync('accessToken')) {
	            // 如果token 存在则跳转到index 页面
	            uni.reLaunch({
	                url: '/pages/index/index'
	            });
	        }
	    }).catch(async err => {
			console.log(err)
	        uni.hideLoading();
	    })

	},
	// 手机号登录
	async phoneLogin({state, dispatch}, data) {
	    return new Promise(async (resolve, reject) => {
	        // 获取手机号
	        phoneLogin({
	            username: data.phone,
	            password: data.code,
	            mode: Env.MODE,
	            app_id: state.appId,
	            login_type: 'phone',
	        }).then(res => {
	            console.log(111, res.data)
	            if (res.data.token) {
	                // 保存token
	                this.commit('setToken', res.data.token)
	                resolve(res)
	            } else {
	                reject(err)
	            }
	            uni.hideLoading();
	        }).catch(err => {
	            console.log(err)
	            reject(err)
	            uni.hideLoading();
	        })
	    })
	},
	// 账号密码
	async pwdLogin({state, dispatch}, data) {
	    return new Promise(async (resolve, reject) => {
			const accountInfo = uni.getAccountInfoSync();
			console.log("accountInfo.miniProgram.appId",accountInfo.miniProgram.appId)
			console.log("state",state)

	        // 密码登录
	        pwdLogin({
	            username: data.username,
	            password: data.password,
	            captcha: data.captcha,
	            captchaKey: data.captchaKey,
	            mode: Env.MODE,
	            app_id: state.appId,
	            login_type: 'pwd',
	        }).then(res => {
	            if (res.data.access) {
	                // 保存token
	                this.commit('setToken', res.data.access)
	                resolve(res)
	            } else {
	                reject(err)
	            }
	            uni.hideLoading();
	        }).catch(err => {
	            console.log(err)
	            reject(err)
	            uni.hideLoading();
	        })
	    })
	}
}


export default {
	actions,
	state,
	mutations,
	getters
}
